﻿namespace ConcurrentBoo.Tests

import System.Threading
import NUnit.Framework

import ConcurrentBoo

[TestFixture]
class ComputationCacheTestFixture:
	
	[Test]
	def GetReturnsImmediately():
		cache = ComputationCache()
		
		started = date.Now
		value = cache.Get("ltuae", { Thread.Sleep(100ms); return 42 })
		assert 100ms > (date.Now - started)
		Assert.AreEqual(42, value.Value)
		
		Assert.AreSame(value, cache.Get("ltuae", null))
		
	[Test]
	def GetTriggersRecomputationUponExpiration():
		cache = ComputationCache(100ms)
		computed = 0
		e as Expression = { ++computed }
		value = cache.Get("computed", e)
		Assert.AreEqual(1, value.Value)
		value = cache.Get("computed", e)
		Assert.AreEqual(1, value.Value)
		Thread.Sleep(150ms)
		value = cache.Get("computed", e)
		Assert.AreEqual(2, value.Value)
		
	[Test]
	def GetTriggersRecomputationUponFailure():
		cache = ComputationCache(1h)
		value = cache.Get("computed", { raise "foo"; return 0 })
		assert value.Failure is not null
		assert value.HasFinishedWithFailure
		
		value = cache.Get("computed", { return 42 })
		Assert.AreEqual(42, value.Value)
		assert not value.HasFinishedWithFailure
		
	
		
		

